package org.elanfox.cloud.common.web.config;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import lombok.Setter;
import org.apache.commons.lang3.StringUtils;
import org.elanfox.cloud.common.base.ApiResult;
import org.elanfox.cloud.common.enums.CommonCode;
import org.elanfox.cloud.common.web.base.JwtProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author allan
 * @version 1.0.0
 * @date 2/24/21
 */
@Setter
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
    private JwtProvider jwtProvider;

    @Autowired
    public JwtAuthenticationFilter(JwtProvider jwtProvider) {
        this.jwtProvider = jwtProvider;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        String token = request.getHeader("Access-Token");
        if (StringUtils.isEmpty(token)) {
            response(response, CommonCode.TOKEN_VERIFY_FAILED);
            return;
        }
        Claims claims = jwtProvider.verify(token);
        if (claims != null) {
            request.setAttribute("claims", claims);
        } else {
            response(response, CommonCode.TOKEN_VERIFY_FAILED);
        }
    }

    private void response(HttpServletResponse response, CommonCode commonCode) throws IOException {
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Cache-Control", "no-cache");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        response.getWriter().println(JSON.toJSONString(ApiResult.exception(commonCode)));
        response.getWriter().flush();
    }
}
